<template>
  <div class="login">
    <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="120px">
      <el-form-item label="username" prop="username" required>
        <el-input v-model="form.username" :prefix-icon="User"/>
      </el-form-item>
      <el-form-item label="password" prop="password" required>
        <el-input v-model="form.password" type="password" show-password :prefix-icon="Lock"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="onSubmit(ruleFormRef)">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import {User, Lock} from '@element-plus/icons-vue'
import {ElNotification} from 'element-plus'
import useUserStore from "@/store/modules/user";
import {useRouter} from "vue-router";
import type { FormInstance } from 'element-plus'

const ruleFormRef = ref()
const form = reactive({
  username: 'admin',
  password: '111111'
})
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (value.length < 6) {
      callback(new Error('密码大于等于六位'))
    }
    callback()
  }
}
const rules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 4, message: '用户名大于等于四位', trigger: 'blur'}
  ],
  // password: [
  //   {required: true, message: '请输入密码', trigger: 'blur'},
  //   {min: 6, message: '密码大于等于六位', trigger: 'blur'}
  // ],
  password: [{ validator: validatePass, trigger: 'blur' }],
})

let loading = ref(false)

let useStore = useUserStore(); //注意点：引入执行函数就可以激活然后使用属性与VUE2要注册不同
let router = useRouter(); //注意点：路由引入

const onSubmit = async (formEl: FormInstance | undefined) => {
  try {
    if (!formEl) return
    await formEl.validate(async(valid, fields) => {
      if (valid) {
        //账号大于四位，密码大于等于六位
        loading.value = true;
        await useStore.userLogin(form)
        await router.push('/')
        ElNotification({
          message: '登录成功',
          type: 'success',
        })
        loading.value = false;
      } else {
        ElNotification({
          message: '检查用户名或密码是否按照正确规则输入',
          type: 'error',
        })
      }
    })
  } catch (e) {
    loading.value = false;
    ElNotification({
      message: e.message,
      type: 'error',
    })
  }


}
</script>

<style lang="scss" scoped>
.login {
  margin: 0;
  display: flex;
  place-items: center;
  min-width: 320px;
  min-height: 100vh;
}
</style>